package cn.good.yan.config.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

/**
 * 自定义登录逻辑
 * 【基于内存的用户认证】 方式2:
 *
 *  AuthorityUtils.commaSeparatedStringToAuthorityList 配置权限和角色
 * @author shengren.yan
 * @create 2024/9/18
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {


    @Autowired
    private PasswordEncoder pw;

    /**
     * 自定义登录逻辑
     *
     * @param userName
     * @return {@link UserDetails }
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        System.out.println("自定义登录逻辑--执行!!!");
        if (!"admin".equals(userName)) {
            throw new UsernameNotFoundException("该用户不存在");
        }
        // 正确的密码，
        String password = pw.encode("123");
        return new User(
                userName,
                password,
                // 权限部分，多个需要，分割
                AuthorityUtils.commaSeparatedStringToAuthorityList("admin,normal,ROLE_normal")
                // 配置权限和角色，角色前面需要带ROLE_，在自定义配置里，hasAnyRole里不需要带ROLE_
//                AuthorityUtils.commaSeparatedStringToAuthorityList("admin,权限,ROLE_角色1,ROLE_角色2")
        );
    }


}
